package com.kollway.android.imagecachelib;

import android.content.Context;
import android.graphics.Bitmap;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;

/**
 * Implementation of volley's ImageCache interface. This manager tracks the application image loader and cache.
 *
 * @author Trey Robinson
 */
public class ImageCacheManager implements ImageCache {

    private static ImageCacheManager mInstance;
    private static int CACHE_SIZE = 20*1024*1024;

    /**
     * Volley image loader
     */
    private ImageLoader mImageLoader;

    /**
     * Image cache used for local image storage
     */
    private DiskLruImageCache mDiskCache;
    
    private ImageCacheManager(Context context) {
    	mDiskCache = new DiskLruImageCache(context, "ImageCache", CACHE_SIZE, Bitmap.CompressFormat.PNG, 80);
        RequestQueue requestQueue = Volley.newRequestQueue(context.getApplicationContext()); 
        mImageLoader = new ImageLoader(requestQueue, this);
	}
    
    /**
     * @return instance of the cache manager
     */
    public static ImageCacheManager getInstance() {
        return mInstance;
    }

    /**
     * Initializer for the manager. Must be called prior to use.
     *
     * @param context        application context
     * @param uniqueName     name for the cache location
     * @param cacheSize      max size for the cache
     * @param compressFormat file type compression format.
     * @param quality
     */
    public static void init(Context context) {
    	if(mInstance == null) {
    		mInstance = new ImageCacheManager(context.getApplicationContext());
    	}
    }

    @Override
    public Bitmap getBitmap(String url) {
        try {
            return mDiskCache.getBitmap(createKey(url));
        } catch (NullPointerException e) {
            throw new IllegalStateException("Disk Cache Not initialized");
        }
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        try {
            mDiskCache.put(createKey(url), bitmap);
        } catch (NullPointerException e) {
            throw new IllegalStateException("Disk Cache Not initialized");
        }
    }

    /**
     * Executes and image load
     *
     * @param url      location of image
     * @param listener Listener for completion
     */
    public void getImage(String url, ImageListener listener) {
        mImageLoader.get(url, listener);
    }

    /**
     * @return instance of the image loader
     */
    public ImageLoader getImageLoader() {
        return mImageLoader;
    }

    /**
     * Creates a unique cache key based on a url value
     *
     * @param url url to be used in key creation
     * @return cache key value
     */
    private String createKey(String url) {
        return String.valueOf(url.hashCode());
    }

}
